package www.openteam.com.tool;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Base64;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

import www.openteam.com.OTApplication;

/**
 * Created by kylin on 2016/12/14.
 */
public class SpUtils {

    /**
     * 保存在手机里的文件名
     */
    public static final String FILE_NAME = "OtAppData";
    static Context context = OTApplication.getmContext();


    public static void put(String key, Object object) {

        SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);

        SharedPreferences.Editor editor = sp.edit();
        if (object instanceof String) {

            editor.putString(key, (String) object);

        } else if (object instanceof Integer) {
            editor.putInt(key, (Integer) object);
        } else if (object instanceof Boolean) {

            editor.putBoolean(key, (Boolean) object);
        } else if (object instanceof Float) {
            editor.putFloat(key, (Float) object);
        } else if (object instanceof Long) {
            editor.putLong(key, (Long) object);
        } else {
            editor.putString(key, object.toString());
        }
        SharePreferencesCompat.apply(editor);
    }

    /**
     *  根据提供的默认值的类型,选择返回值的类型
     * @param key
     * @param defaultObject
     * @return
     */
    public static Object  get(String key,Object defaultObject){
        SharedPreferences sp =context.getSharedPreferences(
                FILE_NAME,Context.MODE_PRIVATE);

        if (defaultObject instanceof String){
            return sp.getString(key, (String) defaultObject);
        } else if (defaultObject instanceof Integer) {
            return sp.getInt(key, (Integer) defaultObject);
        } else if (defaultObject instanceof Boolean) {
            return sp.getBoolean(key, (Boolean) defaultObject);
        } else if (defaultObject instanceof Float) {
            return sp.getFloat(key, (Float) defaultObject);
        } else if (defaultObject instanceof Long) {
            return sp.getLong(key, (Long) defaultObject);
        }
        return null;
    }

    /**
     * 移除某个key对应的值
     * @param key
     */
    public static void remove(String key){
        SharedPreferences sp =context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor =sp.edit();
        editor.remove(key);
        SharePreferencesCompat.apply(editor);
    }

    /**
     * 清除所有数据
     *
     */
    public static void clear(){
        SharedPreferences sp =context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor =sp.edit();
        editor.clear();
        SharePreferencesCompat.apply(editor);
    }


    public static void setObject(String key,Object object){
        SharedPreferences sp =context.getSharedPreferences(
                FILE_NAME,Context.MODE_PRIVATE);

        ByteArrayOutputStream baos=new ByteArrayOutputStream();
        ObjectOutputStream out =null;

        try{
            out =new ObjectOutputStream(baos);
            out.writeObject(object);
            String objectVal =new String (Base64.encode(baos.toByteArray(),Base64.DEFAULT));
            SharedPreferences.Editor editor =sp.edit();
            editor.putString(key,objectVal);
            editor.commit();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try{
                if (baos != null){
                    baos.close();
                }
                if (out != null){
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }


    @SuppressWarnings("unchecked")
    public static <T> T getObject(String key ,Class<T> clazz){
        SharedPreferences sp =context.getSharedPreferences(
                FILE_NAME,Context.MODE_PRIVATE);

        if (sp.contains(key)){
            String objectVal =sp.getString(key,null);
            byte[] buffter =Base64.decode(objectVal,Base64.DEFAULT);
            ByteArrayInputStream bais =new ByteArrayInputStream(buffter);
            ObjectInputStream ois =null;

            try {
                ois =new ObjectInputStream(bais);
                T t = (T) ois.readObject();
                return  t;
            } catch (StreamCorruptedException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }finally {
                try{
                    if (bais != null){
                        bais.close();

                    }
                    if (ois != null){
                        ois.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
        return  null;
    }

    /**
     * 返回所有键值对
     * @return
     */
    public static Map<String,?> getAll(){
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);

        return sp.getAll();
    }


    /**
     * 创建一个解决SharedPreferencesCpmpat.apply方法的兼容类.
     */
    private static class SharePreferencesCompat {
        private static final Method sApplyMethod
                =findApplyMethod();

        /**
         * 反射查找apply的方法
         * @return
         */
        @SuppressWarnings({"unchecked","rawtypes"})
        private static Method findApplyMethod(){
            try{
                Class clz =SharedPreferences.Editor.class;
                return clz.getMethod("apply");
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
            return null;
        }

        /**
         *  如果找到则使用apply执行,否则使用commit
         * @param editor
         */
        public static void apply(SharedPreferences.Editor editor){

            try{
                if (sApplyMethod !=null){
                    sApplyMethod.invoke(editor);
                    return ;
                }
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }

            editor.commit();
        }

    }
    //返回String 值
    public static String getString(Context context,String key ,String defaultStr){
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);
        return sp.getString(key,defaultStr);        }

}
